#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const char* ip = "0.0.0.0";
const int backlog = 10;

class Sock
{
public:
    Sock()
    { }
    void Socket()
    {
        _fd = socket(AF_INET, SOCK_STREAM, 0);
        if(_fd < 0)
        {
            std::cout << "socket error" << std::endl;
        }
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(ip);
        server.sin_port = htons(port);
        if(bind(_fd, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            std::cout << "bind error" << std::endl;
            exit(1);
        }
    }
    void Listen()
    {
        if(listen(_fd, backlog) < 0)
        {
            std::cout << "listen error" << std::endl;
        }
    }
    int Accept(std::string& ip, uint16_t& port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int n = accept(_fd, (struct sockaddr *)&client, &len);
        if(n < 0)
        {
            std::cout << "accept error" << std::endl;
            return -1;
        }
        ip = inet_ntoa(client.sin_addr);
        port = ntohs(client.sin_port);
        return n;
    }
    int Accept()
    {
        int n = accept(_fd, nullptr, nullptr);
        if(n < 0)
        {
            std::cout << "accept error" << std::endl;
            return -1;
        }
        return n;
    }
    int Fd()
    {
        return _fd;
    }

private:
    int _fd;
};